package com.example.wan_android.ui.activity

import android.util.Log
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import com.example.wan_android.BR
import com.example.wan_android.R
import com.example.wan_android.databinding.ActivityWebBinding
import com.example.wan_android.viewmodel.WebViewModel

class WebActivity : BaseActivity<ActivityWebBinding, WebViewModel>(
    WebViewModel::class.java,
    R.layout.activity_web,
    BR.viewModel
) {
    private lateinit var webView: WebView
    override fun initView() {
        webView = findViewById(R.id.webView)

        // 启用基础设置（JavaScript、缩放等）
        webView.settings.javaScriptEnabled = true
        webView.settings.setSupportZoom(true)

        val url = intent.getStringExtra(WebViewModel.url)
        webView.webChromeClient = object : WebChromeClient() {
            // 加载进度变化时回调
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                mViewDataBinding?.progressBar?.progress = newProgress // 更新进度条
                // 进度达到 100% 时隐藏进度条
                if (newProgress == 100) {
                    mViewDataBinding?.progressBar?.visibility = View.GONE
                } else {
                    if (mViewDataBinding?.progressBar?.visibility != View.VISIBLE) {
                        mViewDataBinding?.progressBar?.visibility = View.VISIBLE
                    }
                }
            }
        }
        webView.loadUrl(url!!)
    }

    // 返回键处理
    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    // 生命周期同步
    override fun onResume() {
        super.onResume()
        webView.onResume()
    }

    override fun onPause() {
        super.onPause()
        webView.onPause()
    }

    // 在onDestroy中释放资源
    override fun onDestroy() {
        super.onDestroy()
        webView.apply {
            loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            clearHistory()
            destroy()
        }
    }

}
